import updateTreeNodeInfo, {  getFullTreeByXid, getTreeNodeInfoById, s_getSelectData } from "@/services/basis";
import { CloseOutlined } from "@ant-design/icons";
import { ProCard, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, useStyle } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Card, Col, DatePicker, Flex, Form, Input, message, Radio, Row, Space, Tree, TreeDataNode } from "antd";
import { times } from "lodash";
import moment from "moment";
import { useRef, useState } from "react";

const App:React.FC=()=>{
    const [trNode,setTrNode]=useState<{key:any,title:string}>({key:0,title:''});
    const [trData,setTrData]=useState<TreeDataNode[]>([]);
    const [etype,setEtype]=useState(0);
    const [expandKeys,setExpandKeys]=useState([]);

    const form_ref=useRef<ProFormInstance>();

    useRequest(()=>getFullTreeByXid({x_id:1,treeType:'materialgroup_category'}),{
        onSuccess:(data)=>{
          setTrData(data.ctree);
          setExpandKeys(data.keys);
        },
    });

    async function getTreeNodeInfo(node:{key:any,title:any}){
       // alert(JSON.stringify(node));
        setEtype(0);
        setTrNode(node);//保存当前的id，在新增时使用
       const info=await getTreeNodeInfoById({treeType:'v_materialgroupcategory',key:node.key});
       const fdata={...info.data,
                    operate_time:moment(moment(info.data.operate_time).toDate()).format('YYYY-MM-DD')
             };
      form_ref.current?.setFieldsValue({
                code:fdata.code,name:fdata.name,higher_name:fdata.higher_name,
                operate_time:fdata.operate_time,higher_code:fdata.higher_code,
                status:fdata.status,operater_id:fdata.operater_id,
                }); 
     }

     //新增
     async function add(){
        if(trNode.key==0)
            message.warning('请先选择所归属的类别！');
        else{
         setEtype(1);
         form_ref.current?.resetFields();
         form_ref.current?.setFieldsValue({
            operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),
            higher_code:trNode.title.substring(0,trNode.title.indexOf(' ')),
            higher_name:trNode.title.substring(trNode.title.indexOf(' '+1)),
        });
        };
     };

     //保存
     async function save(){
        const fdata=form_ref.current?.getFieldsValue();
        const fdata2={...fdata,higher_id:trNode?.key, 
                       higher_code:trNode?.title.substring(0,trNode?.title.indexOf(' ')), 
                       id:trNode?.key, 
                      operate_time:moment(moment(fdata.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
       //  alert(JSON.stringify(fdata2));
       //mform_ref.current?.submit();
       const r=await updateTreeNodeInfo({x_id:1,operater_id:1,ttype:etype,tdata:fdata2,treeType:'materialgroup_category'});
        if(r.success){
          message.success('数据保存成功！');
          //alert(JSON.stringify(r.data));
          setTrData(r.data);
          }
        else
          message.error('数据保存失败，请检查。');
    
     }
   
    return(
     <Row gutter={8} >
         <Col span={6}>
         <ProCard title='物料组类别' style={{height:'75vh',overflow:'auto'}}>
            <Tree treeData={trData}   blockNode={true} expandedKeys={expandKeys}
               onClick={(e,node)=>getTreeNodeInfo({key:node.key,title:node.title?.toString()})}
               onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
            />
         </ProCard>
         </Col>
         <Col span={18}>
         <ProCard title='类别基本信息' style={{height:'75vh',overflow:'auto'}} 
              extra={<Space>
                <Button onClick={()=>add()}>新增类别</Button>
                <Button onClick={()=>form_ref.current?.submit()}>保存类别</Button></Space>}>
                {/* {JSON.stringify(trNode)} */}
            <ProForm labelCol={{span:8}} formRef={form_ref} style={{width:500,marginLeft:100}}
               initialValues={{status:1,operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),operater_id:1}}
               submitter={{
                 submitButtonProps:{style:{display:'none'}},
                 resetButtonProps:{style:{display:'none'}}
               }}
               onFinish={()=>save()}
              >
                <ProFormText name='code' label='物料组分类编码' rules={[{required:true,message:'编码必须输入！'}]}/>
                <ProFormText name='name' label='物料组分类名称' rules={[{required:true,message:'名称必须输入！'}]}/>
                <ProFormText name='higher_code' label='上级编码' disabled/>
                <ProFormText name='higher_name' label='上级名称' disabled/>
                <ProFormRadio.Group name='status' label='状态'
                    options={[{label:'正常',value:1},{label:'冻结',value:2,style:{color:'blue'}},{label:'删除',value:3,style:{color:'red'}}]}
                    />
                <Row gutter={8}>
                  <Col span={12}>
                          <ProFormDatePicker name='operate_time' label='修改时间' />
                  </Col>
                  <Col span={12}>
                  <ProFormSelect name='operater_id' label='修改人' 
                       showSearch
                                   request={async ()=>{
                                          const x=await s_getSelectData({x_id:1,source:'base_person'});
                                           return x.data;
                                     }}
                  />
                  </Col>
                </Row>
             </ProForm>
         </ProCard>
         </Col>
     </Row>
);
}

export default App;